﻿//
//
// 版权所有 (c) 2021-2023 JR  
//
// 特此免费授予获得本软件的任何人以处理本软件的权利，但须遵守以下条件：在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
//
// 软件按“原样”提供，不提供任何形式的明示或暗示的保证，包括但不限于对适销性、适用性和非侵权的保证。
// 在任何情况下，作者或版权持有人均不对任何索赔、损害或其他责任负责，无论是因合同、侵权或其他方式引起的，与软件或其使用或其他交易有关。

using Elasticsearch.Net;
using Furion.Schedule;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EMC.VISITOR.Core;
public abstract class BaseJob
{
    protected readonly IServiceProvider _serviceProvider;
    public BaseJob(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }
    public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
    {


        SysLogAutoTask log = new SysLogAutoTask();
        log.CreateTime = DateTime.Now;
        log.TaskName = context.JobDetail.Description;
        var paramter = context.JobDetail.Properties;
        var triggerId = context.TriggerId;
        //var triggerService = serviceScope.ServiceProvider.GetService<SqlSugarRepository<SysJobTrigger>>();
        Stopwatch sp = new Stopwatch();
        sp.Start();
        try
        {
            var result = await Run(log, paramter);
            log = result.Item1;
            if ((log.Logtype == "WXSEND" || log.Logtype == "HKFACECHECK" || log.Logtype == "HK" || log.Logtype == "FLOW") && !result.Item2.IsNullOrEmpty() && result.Item2.ObjToInt() <= 0)
            {
                return;
            }
        }
        catch (Exception ex)
        {
            log.Error = ex.ToString();
        }
        sp.Stop();
        log.Elapsed = sp.Elapsed.TotalMilliseconds.ToString("00");
        try
        {
            using var iTenant = App.GetRequiredService<ISqlSugarClient>();
            using var autoTask = iTenant.AsTenant().GetConnectionScope(SqlSugarConst.LogConfigId);
            await autoTask.MyInsertable(log).ExecuteCommandAsync();
            //using (var serviceScope = _serviceProvider.CreateScope())
            //{
            //    var autoTask = serviceScope.ServiceProvider.GetRequiredService<SqlSugarRepository<SysLogAudit>>();
            //await autoTask.MyInsertable(log).ExecuteCommandAsync();
            //}
        }
        catch (Exception ex)
        {
            MyLogHelper.AddLog(log.Message + " | " + ex.ToString(), "自动任务插入SysLogAutoTask错误！", null);
        }
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="log">日志</param>
    /// <param name="paramter">请求参数</param>
    /// <param name="triggerId">触发器Id</param>
    /// <param name="triggerId"></param>
    /// <returns></returns>
    public abstract Task<Tuple<SysLogAutoTask, string>> Run(SysLogAutoTask log, string paramter);
}
